package com.ljh.myaiagent.tools;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import com.ljh.myaiagent.constant.FileConstant;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

/**
 * 文件操作工具类
 */
public class FileOperationTool {
    private final String FILE_SAVE_DIR = FileConstant.FILE_SAVE_DIR;

    @Tool(description = "Read content from a file")
    public String readFile(@ToolParam(description = "Name of the file to read") String fileName) {
        String path = FILE_SAVE_DIR + "/" + fileName;
        try {
            return FileUtil.readUtf8String(path);
        } catch (IORuntimeException e) {
            return "Error: Unable to read file " + fileName + ". " + e.getMessage();
        }
    }

    @Tool(description = "Write content to a file")
    public String writeFile(@ToolParam(description = "Name of the file to write") String fileName,
                            @ToolParam(description = "Content to write to the file") String content){
        String path = FILE_SAVE_DIR + "/" + fileName;
        try {
            FileUtil.mkdir(FILE_SAVE_DIR);
            FileUtil.writeUtf8String(content, path);    // 覆盖写
            return "File " + fileName + " written successfully.";
        } catch (IORuntimeException e) {
            return "Error: Unable to write file " + fileName + ". " + e.getMessage();
        }
    }
}
